<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> HLS 私有加密 - TCPlayer</title>
    <style>
        h1 {
            font-weight: normal;
        }
    </style>
</head>
<body>

<h1> HLS 私有加密 - TCPlayer</h1>

<video id="container" preload="auto" width="600" controls playsinline webkit-playsinline></video>
<link href="https://web.sdk.qcloud.com/player/tcplayer/release/v4.5.0/tcplayer.min.css" rel="stylesheet">
<script src="https://web.sdk.qcloud.com/player/tcplayer/release/v4.5.0/libs/hls.min.0.13.2m.js"></script>
<script src="https://web.sdk.qcloud.com/player/tcplayer/release/v4.5.0/tcplayer.v4.5.0.min.js"></script>
<script src="cos_hls_sdk.js"></script>
<script>
    // 请求服务端获取带有 token 和 签名 的 playUrl
    const getPlayUrl = function (opt) {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.withCredentials = true;
            xhr.open('POST', `/hls/getPlayUrl`, true);
            xhr.setRequestHeader('Content-Type', 'application/json')
            xhr.onload = function () {
                var r = JSON.parse(xhr.responseText);
                resolve(r.playUrl);
            };
            xhr.onerror = function () {
                reject('get getPlayUrl error');
            };
            var data = {
                // 这里根据业务需要，可以传自己业务逻辑里的视频 id，方便服务端知晓是播放哪个 objectKey
                objectKey: opt.objectKey,
                // publicKey、protectContentKey 是需要透传到服务端的参数
                publicKey: opt.publicKey,
                protectContentKey: opt.protectContentKey,
            };
            xhr.send(JSON.stringify(data));
        });
    };
    // 播放视频
    const playVideo = async function () {
        const params = CosHlsSdk.createTokenParams();
        const opt = {
            objectKey: 'encrypt/bunny.m3u8',
            publicKey: params.publicKey,
            protectContentKey: params.protectContentKey,
        };
        const playUrl = await getPlayUrl(opt);
        const { player } = CosHlsSdk.play({
            container: '#container',
            playerType: 'tcplayer',
            playUrl: playUrl,
        });
        console.log(player);
    };
    playVideo();
</script>

</body>
</html>

